package yqt.com.cnki.controller;


import com.alibaba.fastjson.JSONObject;
import haha.life.common.CutPageBean;
import haha.life.normal.DealJsonUtils;
import io.swagger.annotations.ApiOperation;
import jzqb.common.Result;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yqt.com.cnki.bo.*;
import yqt.com.cnki.service.KnowledgeYqtService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/knowledge")
public class KnowledgeYqtController {


    @Autowired
    KnowledgeYqtService knowledgeService;

    @GetMapping("/getIndex")
    public Result getIndex() {
        String jsonStr = DealJsonUtils.readJsonFile("dbyqt.json");
        JSONArray listArray = JSONArray.fromObject(jsonStr);
        List<DbBo> list = JSONObject.parseArray(listArray.toString(), DbBo.class);
//        for (DbBo dbBo : list) {
//            if (!dbBo.getIsOutResource()) {
//                String nodeCode = dbBo.getDbNodeCode();
//                List<Nodebo> Nodebos = knowledgeService.getNodeByTableName(nodeCode);
//                List<DbPartBo> dbPartBos = new ArrayList<>();
//                for (Nodebo nodebo : Nodebos) {
//                    DbPartBo dbPartBo = new DbPartBo();
//                    dbPartBo.setDbCode(dbBo.getDbCode());
//                    dbPartBo.setShowName(nodebo.getName());
//                    dbPartBo.setClassifyCode(nodebo.getCode());
//                    dbPartBo.setIsOutResource(false);
//                    dbPartBo.setIsfz(dbBo.getIsfz());
//                    dbPartBo.setDbSource(dbBo.getShowName());
//                    dbPartBos.add(dbPartBo);
//                }
//                dbBo.setResourceList(dbPartBos);
//            }
//        }
        return Result.succ(list);
    }

    @GetMapping("/getSearchItem")
    public Result getSearchItem() {
        String jsonStr = DealJsonUtils.readJsonFile("search.json");
        JSONArray listArray = JSONArray.fromObject(jsonStr);
        return Result.succ(listArray.toString());
    }

    @PostMapping("/complexSearch")
    public CutPageBean<KnowledgeBo> complexSearch(@RequestBody KnowledgeBo knowledgeBo) {
        CutPageBean<KnowledgeBo> cutPageBean = new CutPageBean<>();
        knowledgeBo.setStart((knowledgeBo.getPage() - 1) * knowledgeBo.getPageSize());
        String key = knowledgeBo.getSearchKeyWord();
        String value = knowledgeBo.getSearchValue();
        String conditionSql = knowledgeBo.getConditionSql();
        // 高级检索的 beginDate
        String beginDate = knowledgeBo.getBeginDate();
        // 高级检索的endDate
        String endDate = knowledgeBo.getEndDate();
        // 高级检索的LimitData
        String limitData = knowledgeBo.getLimitData();
        // orderBy value
        String orderByValue = knowledgeBo.getOrderByValue();
        // orderBy sort
        String orderBySort = knowledgeBo.getOrderBySort();
        //这里是数据来源Bo
        List<StandConditionBo> standConditionBos = knowledgeBo.getStandConditionBoList();
        //拿到前半部分关于dbSource的限制
        String sqlPre = getSQLPre(standConditionBos);
        //拿到前半部分关于dbSourceCount的限制
        String sqlPreCount = getSQLCountPre(standConditionBos);
        // 中间部分SearchKeyWord value 拼接 条件拼接
        String midStr = getSQLMid(key, value, conditionSql, beginDate, endDate, limitData);
        // 这里是对orderBy 和midStr 的处理
        String after = sqlPre + midStr;
        String afterCount = sqlPreCount + midStr;
        if (orderByValue != null && orderByValue != "") {
            after = after + " order by " + orderByValue;
        }
        if (orderBySort != null && orderBySort != "") {
            after = after + " " + orderBySort;
        }
        knowledgeBo.setSql(after);
        knowledgeBo.setSqlCount(afterCount);
        List<KnowledgeBo> knowledgeBoList = knowledgeService.complexSearch(knowledgeBo);
        Long count = knowledgeService.findComplexSearchCount(knowledgeBo);
        for (KnowledgeBo bo : knowledgeBoList) {
            String str = bo.getTitle().replaceAll("\\<.*?\\>", "");
            String Result = StringEscapeUtils.unescapeHtml(str);
            bo.setTansTitle(Result);
        }
        cutPageBean.initCutPage(count.intValue(), knowledgeBo.getPageSize(), knowledgeBoList);
        return cutPageBean;
    }

    /*--------------检索项提示词-----------------------*/
    @ApiOperation(value = "检索项提示词")
    @PostMapping("/getCueWord")
    public Result getCueWord(@RequestBody Map<String, String> map) {
        String inputWord = map.get("inputWord");
        if ("".equals(inputWord) || inputWord == null) {
            return Result.succ(null);
        }
        String inputWordStr=inputWord+"?";
        //select top 10 keyword from SYS_XLDICT where keyword='鸭?' group by keyword order by relevant
        List<String> cueWordList = knowledgeService.getCueWord(inputWordStr);
        return Result.succ(cueWordList);
    }


    private String getSQLMid(String key, String value, String conditionSql, String beginDate, String endDate, String LimitData) {
        StringBuilder stringBuilder = new StringBuilder(" ");
        //拼接keyWord 和value
        if (key != null && key != null && value != "" && value != "") {
//            stringBuilder.append(" ").append("AND ").append(key).append(" % ").append("\"").append(value).append("\"");
            stringBuilder.append(" ").append(key).append(" % ").append("\"").append(value).append("\"");
        }
        if (conditionSql != null && conditionSql != "") {
//            stringBuilder.append("  and  ").append(conditionSql).append(" ");
            stringBuilder.append(conditionSql).append(" ");
        }
        //begainDate
        if (beginDate != null && beginDate != "") {
            String res = " AND 发表时间 > " + "\"" + beginDate + "\"";
            stringBuilder.append(res).append(" ");
        }
        //endDate
        if (endDate != null && endDate != "") {
            String res = " AND 发表时间 < " + "\"" + endDate + "\"";
            stringBuilder.append(res).append(" ");
        }
        //LimitData
        if (LimitData != null && LimitData != "") {
            long mill = System.currentTimeMillis();
            if ("最近一周".equals(LimitData)) {
                mill -= 86400000l * 7;
            } else if ("最近一月".equals(LimitData)) {
                mill -= 86400000l * 31;
            } else if ("最近半年".equals(LimitData)) {
                mill -= 86400000l * 30.5 * 6;
            } else if ("最近一年".equals(LimitData)) {
                mill -= 86400000l * 365;
            }
            // LimitData 不为null
            String dataStr = new SimpleDateFormat("yyyy-MM-dd").format(mill);
            if (dataStr != null && dataStr != "") {
                String res = " AND  发表时间 > " + "\"" + dataStr + "\"";
                stringBuilder.append(res).append(" ");
            }
        }
        return stringBuilder.toString();
    }

    private String getSQLPre(List<StandConditionBo> standConditionBos) {
        StringBuilder sql = new StringBuilder("SELECT 题名,*,发表时间,SYS_FLD_SYSID FROM ");
        for (StandConditionBo standConditionBo : standConditionBos) {
            sql.append(standConditionBo.getDbCode()).append(" ,");
        }

        String finalStr = sql.toString();
        if (finalStr.endsWith(",")) {
            finalStr = finalStr.substring(0, finalStr.length() - 1);
        }

        Boolean begain = true;
        for (StandConditionBo standConditionBo : standConditionBos) {
            List<String> StrList = standConditionBo.getClassifyCodes();
            if (StrList == null || StrList.size() == 0) {
            } else {
                if (begain) {
                    finalStr = finalStr + " where ((题名=* not 分类=* ) ";
                    begain = false;
                }
                for (String s : StrList) {
                    finalStr = finalStr + " or 分类= " + s + " ";
                }
            }
        }
        if (!begain) {
            finalStr = finalStr + " )  ";
        } else {
//            finalStr = finalStr + "where 题名= *";
            finalStr = finalStr + "where ";
        }
        return finalStr;
    }

    private String getSQLCountPre(List<StandConditionBo> standConditionBos) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ");
        for (StandConditionBo standConditionBo : standConditionBos) {
            sql.append(standConditionBo.getDbCode()).append(" ,");
        }

        String finalStr = sql.toString();
        if (finalStr.endsWith(",")) {
            finalStr = finalStr.substring(0, finalStr.length() - 1);
        }

        Boolean begain = true;
        for (StandConditionBo standConditionBo : standConditionBos) {
            List<String> StrList = standConditionBo.getClassifyCodes();
            if (StrList == null || StrList.size() == 0) {
            } else {
                if (begain) {
                    finalStr = finalStr + " where ((题名=* not 分类=* ) ";
                    begain = false;
                }
                for (String s : StrList) {
                    finalStr = finalStr + " or 分类= " + s + " ";
                }
            }
        }
        if (!begain) {
            finalStr = finalStr + " ) ";
        } else {
//            finalStr = finalStr + "where 题名= *";
            finalStr = finalStr + "where ";
        }
        return finalStr;
    }


}
